using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class Bat : MonoBehaviour {
	public Transform visual;
	public Vector3Int dir;
	public float moveInterval;

	private TimeFlag m_moveFlag;

	public Transform sprTransform;

	private void Update() {
		if (!m_moveFlag.LessThan(moveInterval)) {
			m_moveFlag.SetTrue();

			UpdateDir();
			var tilePos = TilemapDataManager.Instance.GetTilePosition(transform.position);
			var playerTilePos = TilemapDataManager.Instance.GetTilePosition(PlayerEntity.Instance.transform.position);
			if (playerTilePos - tilePos == dir) {
				visual.DOPunchPosition((Vector3)dir * 0.3f, 0.2f);
				BattleFlowController.Instance.AttackPlayer(1);
			} else {
				tilePos += dir;
				var nextPos = TilemapDataManager.Instance.GetWorldPosition(tilePos);

				var diff = nextPos - transform.position;

				// set the transform pos
				transform.position = nextPos;
				
				// dotween the spr transform
				sprTransform.localPosition = -diff;
				sprTransform.DOLocalMove(Vector3.zero, 0.1f);
				
				// transform.DOMove(nextPos, 0.1f);
			}
		}
	}

	private void UpdateDir() {
		var pos = transform.position;
		var tilePos = TilemapDataManager.Instance.GetTilePosition(pos);
		var forward = tilePos + dir;

		if (dir != Vector3.zero && TilemapDataManager.Instance.IsMon3trWalkable(forward)) {
			return;
		}

		dir = TilemapDataManager.Instance.GetMon3trWalkableDir(tilePos);
	}
}
